package com.newgrand.annexserver.datasource;

import com.newgrand.annexcommon.constant.DBUserTypeConstants;
import com.newgrand.annexcommon.model.DbConfigEnity;
import com.newgrand.annexserver.beans.Dbconfig;

import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;

/**
 * ngsoft 数据库上下文
 */
public class NgDataSourceContextHolder {

    public static String defaultDataSourceKey = "ngsoftDataSource";

    private static final ThreadLocal<String> CONTEXT_HOLDER_DATASOURCE = ThreadLocal.withInitial(() -> new String(defaultDataSourceKey));//业务数据源key

    public static String getDataSourceKey() {
        return CONTEXT_HOLDER_DATASOURCE.get();
    }

    public static void setDataSourceKey(String key) {
        CONTEXT_HOLDER_DATASOURCE.set(key);
    }

    public static void setBusinessDataSourceKey(Dbconfig dbconfig) {
        DbConfigEnity enity1 = new DbConfigEnity();
        enity1.setDbtoken(dbconfig.getDbtoken());
        enity1.setdBUserType(DBUserTypeConstants.business_type);
        enity1.setDriverClassName(dbconfig.getDriverClassName());
        enity1.setUrl(dbconfig.getUrl());
        enity1.setPassword(dbconfig.getPassword());
        enity1.setUsername(dbconfig.getUsername());
        String dataSourceKey = NgDynamicDataSourceBeanRegistry.generateNgBeanName(enity1);
        CONTEXT_HOLDER_DATASOURCE.set(dataSourceKey);
    }

    public static void setStoreDataSourceKey(Dbconfig dbconfig) {
        DbConfigEnity enity1 = new DbConfigEnity();
        enity1.setDbtoken(dbconfig.getDbtoken());
        enity1.setdBUserType(DBUserTypeConstants.store_type);
        enity1.setDriverClassName(dbconfig.getStoreDriverClassName());
        enity1.setUrl(dbconfig.getStoreUrl());
        enity1.setPassword(dbconfig.getStorePassword());
        enity1.setUsername(dbconfig.getStoreUsername());
        String dataSourceKey = NgDynamicDataSourceBeanRegistry.generateNgBeanName(enity1);
        CONTEXT_HOLDER_DATASOURCE.set(dataSourceKey);
    }

    public static void clearDataSourceKey() {
        CONTEXT_HOLDER_DATASOURCE.remove();
    }


}
